<?php

namespace App\Console\Commands;

use App\Models\SwtMerchant;
use App\Models\SwtMerchantMachine;
use App\Models\SwtMerchantProfit;
use App\Services\AdminService;
use Illuminate\Console\Command;

class DeviceProfit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'device_profit:worker';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每日用户补偿分润处理';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $day = date('Y-m-d', strtotime('-1 day', time()));

        //获取虚拟机补充收益
        $virtual_compensation = $this->setVirtualDeviceCompensation();

        //获取实体机补充收益
        $compensation = $this->setDeviceCompensation($day);

        $list = array_merge($virtual_compensation, $compensation);

        $item = [];

        foreach ($list as $v) {
            if (!isset($item[$v['user_id']])) {
                $item[$v['user_id']] = $v;
            } else {
                $item[$v['user_id']]['profit_amount'] += $v['profit_amount'];
            }
        }

        try {
            $num = 0;

            foreach($item as $v) {
                $res = AdminService::setDeviceCompensation($v);
                if($res) {
                    $num ++;
                }
            }

            echo "成功".$num."条";
        } catch (\Exception $e) {
            echo "失败：".$e->getMessage();
        }
    }

    /**
     * @notes 设置虚拟机分润
     * @return array
     * @author Evil丿
     * @date 2024/11/22 12:24
     */
    public function setVirtualDeviceCompensation()
    {
        $list = SwtMerchant::whereNotNull('shop_user_id')
            -> where('virtual_device_num', '>', 0)
            -> where('compensation','>',0)
            -> get()
            -> toArray();

        $arr = [];

        foreach($list as $v) {
            $arr[] = [
              'user_id'         => $v['shop_user_id'],
              'profit_amount'   => $v['virtual_device_num'] * $v['compensation']
            ];
        }

        return $arr;
    }

    /**
     * @notes 真实设备补贴收益
     * @return array
     * @author Evil丿
     * @date 2024/11/22 12:34
     */
    public function setDeviceCompensation($day)
    {
        $owner_list = SwtMerchantMachine::leftJoin('swt_merchant','swt_merchant_machine.merchant_id','=','swt_merchant.id')
            -> select('swt_merchant_machine.*','swt_merchant.compensation', 'swt_merchant.deposit','swt_merchant.shop_user_id')
            -> where('is_owner', 1)
            -> whereNotNull('shop_user_id')
            -> where('compensation','>',0)
            -> get();

        if($owner_list) {
            $owner_list = $owner_list -> toArray();
        } else {
            return [];
        }

        $list = [];
        foreach($owner_list as $v) {
            $amount = SwtMerchantProfit::where('merchant_id', $v['merchant_id'])
                ->where('machine_id', $v['machine_id'])
                ->whereDate('created_at', $day)
                ->selectRaw('type, sum(profit) as amount')
                ->groupBy('type')
                ->get();

            if(count($amount) > 0) {
                $v['total'] = 0;

                foreach ($amount as $a) {
                    if ($a['type'] == 0) {
                        $v['total'] += $a['amount'];
                    } else {
                        $v['total'] -= $a['amount'];
                    }
                }

                if ($v['total'] <= 0) {
                    continue;
                }

                $v['total'] = $v['total'] / 100;

                $v['profit_amount'] = $v['compensation'] - $v['total'];

                if ($v['profit_amount'] <= 0) {
                    continue;
                }
            } else {
                $v['profit_amount'] = $v['compensation'];
            }

            $list[] =  [
                'user_id'         => $v['shop_user_id'],
                'profit_amount'   => $v['profit_amount']
            ];

            //补贴收益至货款
            $deposit_now = $v['deposit_now'] + $v['profit_amount'];

            SwtMerchantMachine::where('id', $v['id']) -> update(['deposit_now' => $deposit_now < $v['deposit'] ? $deposit_now : $v['deposit']]);

        }

        return $list;
    }
}
